import { useState, useEffect, useContext } from 'react';
import { PhoneOutlined, AudioOutlined } from '@ant-design/icons';
import { Toast } from 'antd-mobile';
import AvatarImage from '../AvatarImage';
import Rtc from '../../page/Chat/Rtc';
import { observer } from "mobx-react-lite";
import { ContentType } from '../../constants';
import { MySdkStoreContext } from '../../context';
import { globalJump } from '../../utils';

import './style.scss';

export default observer(function(props) {
  const { cid, from } = props;
  console.log('NewMessageTopBar rtc props', props);
  const [rtcReceiveProps, setRtcReceiveProps] = useState({ visible: false });
  const mySdkStore =  useContext(MySdkStoreContext);
  // 音视频组件props
  const [rtcPageProps, setRtcPageProps] = useState({ visible: false });

  const handleToRtcReceivePage = () => {
    setRtcReceiveProps({ ...props, visible: true, });
  }

  // 用户挂断监听事件
  const onParticipantLeaveRtcRoom = (res) => {
    const { leaveUserId } = res;
    Toast.show(`${leaveUserId}已挂断`);
    mySdkStore.setNewMessageTopBarProps({
      visible: false
    });
  }

  useEffect(() => {
    mySdkStore.sdk.onParticipantLeaveRtcRoom = onParticipantLeaveRtcRoom;
  }, []);

  // 点击”拒绝“按钮事件处理
  const handleReject = async (e) => {
    e.stopPropagation();
    const msgBody: any = {
      msgType: ContentType.Rtc,
      msgContent: { rtcAction: 'rejectInvite' },
    };
    if(cid) {
      msgBody.toCid = cid
    }
    const msgParams = mySdkStore.sdk.messageBuilder(msgBody);
    mySdkStore.sdk.sendMessage(msgParams).then(() => {
      mySdkStore.setCurrentMeetingInfo(null);
    });
    mySdkStore.setNewMessageTopBarProps({
      visible: false
    });
  };

  // 点击”接听“图标事件处理，发送”接听“消息后，进入音视频页面
  const handleAccept = async (e) => {
    if (cid) {
      mySdkStore.sdk.setCurrentCid(cid);
    }
    if(mySdkStore.currentMeetingInfo && mySdkStore.currentMeetingInfo.cid) {
      mySdkStore.setNewMessageTopBarProps({
        visible: false
      });
      globalJump(`#/meetingDetail/${mySdkStore.currentMeetingInfo.cid}`);
      return;
    }
    e.stopPropagation();
    const msgBody: any = {
      msgType: ContentType.Rtc,
      msgContent: { 
        rtcAction: 'acceptInvite',
        rtcSlot: {
          publishVideoElementId: 'implusPublishVideoElementId',
          subscribeVideoElementId: 'implusSubscribeVideoElementId',
          subscribeAudioElementId: 'implusSubscribeAudioElementId'
        },
       }//, rtcType: 'AUDIO'
    };
    if(cid) {
      msgBody.toCid = cid;
    }
    const msgParams = mySdkStore.sdk.messageBuilder(msgBody);
    try{
    mySdkStore.sdk.sendMessage(msgParams);
    } catch {
      Toast.show('接入失败');
    }
    setRtcPageProps({
      visible: true,
      isVedio: true,
      rtcAction: 'continue',
      isVedioEnable: true,
      cid,
      onClose: () => { 
        setRtcPageProps({ visible: false });
        mySdkStore.setNewMessageTopBarProps({
          visible: false
        });
      }
    });
  }

  // 处理”语音接听“图标事件
  const handleAcceptByAudio = async (e) => {
    if (cid) {
      mySdkStore.sdk.setCurrentCid(cid);
    }
    if(mySdkStore.currentMeetingInfo && mySdkStore.currentMeetingInfo.cid) {
      globalJump(`#/meetingDetail/${mySdkStore.currentMeetingInfo.cid}`);
      return;
    }
    e.stopPropagation();
    const msgBody: any = {
      msgType: ContentType.Rtc,
      msgContent: { rtcAction: 'acceptInvite' }
    };
    if(cid) {
      msgBody.toCid = cid;
    }
    const msgParams = mySdkStore.sdk.messageBuilder(msgBody);
    try {
        await mySdkStore.sdk.sendMessage(msgParams);
    } catch {
      Toast.show('接入失败');
    }
    setRtcPageProps({
      visible: true,
      isVedioEnable: false,
      rtcAction: 'continue',
      cid,
      onClose: () => { 
        setRtcPageProps({ visible: false }); 
        mySdkStore.setNewMessageTopBarProps({
          visible: false
        });
      }
    });
  }

  return <div className="rtcNewMessageComponent" onClick={handleToRtcReceivePage}>
    <div className="userInfoBar">
      <AvatarImage
        src={from?.avatarUrl}
        style={{ marginRight: 12, borderRadius: '8px' }}
        fit='cover'
        width={42}
        height={42}
        nickName={from?.nickName}
        userName={from?.userName}
        userId={from?.userId}
      />
      <div>
        {from.userName || from.userId}邀请你加入
        <div className="meetingName">{from.userName || from.userId}发起的视频会议</div>
      </div>
    </div>
    <div className="bottomIconBar">
    <div>
      <div className="iconWrap">
        <AudioOutlined style={{ fontSize: 20, color: '#fff', lineHeight: '38px' }} onClick={handleAcceptByAudio} />
      </div>
    </div>
    <div>
      <div className="iconWrap hangup" style={{ marginRight: 22 }} onClick={handleReject}>
        <PhoneOutlined style={{ fontSize: 20, color: '#fff', lineHeight: '38px', transform: 'rotate(225deg) translate(-0.5px, 2px)' }} />
      </div>
      <div className="iconWrap hangon" onClick={handleAccept}>
        <PhoneOutlined style={{ fontSize: 20, color: '#fff', lineHeight: '38px', transform: 'translate(0,1.5px)' }} />
      </div>
      </div>
    </div>
    {/* { rtcReceiveProps.visible && <RtcReceive {...rtcReceiveProps} />} */}
    { rtcPageProps.visible && <Rtc {...rtcPageProps} />}
  </div>
})